<template>
  <div>
    <el-row>
      <el-col :lg="12" :xl="10">
        <el-select
          v-model="templateId"
          placeholder="请选择运费模板"
          clearable
          :style="{ width: '100%' }"
        >
          <el-option
            v-for="item in templateList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-col>
      <el-col :lg="12" :xl="14">
        <el-button class="ml-10 ft-12" type="text" @click="refresh">刷新</el-button>
      </el-col>
    </el-row>
    <div class="mt-20">
      <el-row>
        <el-col :lg="24" :xl="20">
          <PageTable :columns="columns" :data="dataSource" />
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script>
export default {
  name: 'SelectTemplate',
  components: {},
  props: {
    value: [String, Number]
  },
  data() {
    return {
      templateList: [],
      dataSource: [],
      columns: [
        {
          label: '配送区域',
          render: (h, { row }) => {
            return <div>{row.areaNames || '默认运费'}</div>
          }
        },
        {
          prop: 'firstValue',
          label: '首重（kg）'
        },
        {
          prop: 'firstCashPrice',
          label: '运费（元）'
        },
        {
          prop: 'incrementValue',
          label: '续重（kg）'
        },
        {
          prop: 'incrementCashPrice',
          label: '续费（元）'
        }
      ]
    }
  },
  computed: {
    templateId: {
      get() {
        return this.value
      },
      set(id) {
        this.$emit('input', id)
      }
    }
  },
  watch: {
    templateId: {
      immediate: true,
      handler(newValue) {
        if (!newValue) return
        this.getExpressTemplateDetail()
      }
    }
  },
  created() {
    this.getExpressList()
  },
  mounted() {},
  methods: {
    // 获取模板列表
    async getExpressList() {
      try {
        const { data } = await this.$http.express.templateApi.getExpressTemplateListAll()
        this.templateList = data
      } catch (error) {
        console.log('getExpressList', error)
      }
    },

    // 获取快递模板详情
    async getExpressTemplateDetail() {
      try {
        const {
          data: { defaultCharge, listCharge }
        } = await this.$http.express.templateApi.getExpressTemplateDetail(this.templateId)
        this.dataSource = defaultCharge ? [defaultCharge, ...listCharge] : listCharge
      } catch (error) {
        console.log('getExpressTemplateDetail', error)
      }
    },

    // 点击刷新
    async refresh() {
      await this.getExpressList()
      if (this.templateId) {
        await this.getExpressTemplateDetail()
      }
      this.$message.success('刷新成功')
    }
  }
}
</script>

<style lang="scss" scoped></style>
